<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 客户回收站管理
 * @icon fa fa-user
 */
class Budrecycle extends Backend
{
  // 开启关联查询
  protected $relationSearch = true;

  // 快速查询，搜索指定的哪些字段
  protected $searchFields = 'id,nickname,source.name';

  /**
   * 当前对象模型
   */
  protected $model = null;

  // 管理员模型
  protected $AdminModel = null;

  public function _initialize()
  {
    parent::_initialize();

    // 全局用户模型
    $this->model = model('Business.Business');
    $this->AdminModel = model('Admin');
  }

  // 查看
  public function index()
  {
    //设置过滤方法
    $this->request->filter(['strip_tags']);
    if ($this->request->isAjax()) {

      if ($this->request->request('keyField')) {
        return $this->selectpage();
      }

      list($where, $sort, $order, $offset, $limit) = $this->buildparams();

      $total = $this->model
        ->onlyTrashed()
        ->with(['source', 'admin'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->count();  //查询总数

      $list = $this->model
        ->onlyTrashed()
        ->with(['source', 'admin'])
        ->where($where)
        ->order($sort, $order)
        ->limit($offset, $limit)
        ->select();  //查询数据

      $result = array("total" => $total, "rows" => $list);

      return json($result);
    }
    return $this->view->fetch();
  }

  // 删除
  public function del($ids = null)
  {
    $id = empty($ids) ? [] : explode(',', $ids);

    // 用户图片列表
    $avatarList = [];

    // 判断是否有没有当前数据
    foreach ($id as $item) {
      // onlyTrashed()  仅查询软删除数据
      $res = $this->model->onlyTrashed()->find($item);
      if (!$res) {
        $this->error('未找当前用户');
      }

      // 获取选中的用户头像地址并且追加数组里
      array_push($avatarList, $res['avatar']);
    }

    // 过滤
    $avatarList = array_filter($avatarList);

    $result = $this->model->destroy($id, true);

    if ($result) {
      // 批量删除用户图片
      foreach ($avatarList as $val) {
        $src = substr($val, 1);
        @is_file($src) && @unlink($src);
      }

      $this->success('删除成功');
    } else {
      $this->error($this->model->getError());
    }
  }

  // 还原
  public function reduction($ids = null)
  {
    $id = empty($ids) ? [] : explode(',', $ids);

    // 判断是否有没有当前数据
    foreach ($id as $item) {
      $res = $this->model->onlyTrashed()->find($item);
      if (!$res) {
        $this->error('未找当前用户');
      }
    }

    $wheres = [
      'id' => ['in', $id]
    ];

    $result = $this->model->onlyTrashed()->where($wheres)->update(['deletetime' => null]);

    if ($result) {
      $this->success('还原成功');
    } else {
      $this->error($this->model->getError());
    }
  }
}
